from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
import sys
import os

# 添加项目根目录到 Python 路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.database import SQLALCHEMY_DATABASE_URL

def check_database():
    """检查数据库状态"""
    # 创建数据库连接
    engine = create_engine(SQLALCHEMY_DATABASE_URL)
    Session = sessionmaker(bind=engine)
    db = Session()

    try:
        # 检查学生总数
        result = db.execute(text("SELECT COUNT(*) FROM students"))
        total_students = result.scalar()
        print(f"\n数据库中共有 {total_students} 名学生")

        # 检查年级分布
        result = db.execute(text("""
            SELECT grade, COUNT(*) as count 
            FROM students 
            GROUP BY grade 
            ORDER BY grade
        """))
        stats = result.fetchall()
        
        print("\n年级分布：")
        for grade, count in stats:
            print(f"大{grade if grade is not None else '未设置'}：{count}人")

        # 检查没有年级信息的学生
        result = db.execute(text("SELECT COUNT(*) FROM students WHERE grade IS NULL"))
        null_count = result.scalar()
        if null_count > 0:
            print(f"\n警告：有 {null_count} 名学生没有年级信息")
            
            # 显示这些学生的详细信息
            result = db.execute(text("""
                SELECT id, student_id, name 
                FROM students 
                WHERE grade IS NULL 
                LIMIT 5
            """))
            print("\n以下是部分没有年级信息的学生：")
            for id, student_id, name in result:
                print(f"ID: {id}, 学号: {student_id}, 姓名: {name}")

    except Exception as e:
        print(f"检查过程中发生错误: {str(e)}")
    finally:
        db.close()

if __name__ == "__main__":
    check_database() 